<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>本地知识库问答系统</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background-color: white;
            border-radius: 10px;
            padding: 30px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 30px;
        }
        .tabs {
            display: flex;
            margin-bottom: 20px;
            border-bottom: 1px solid #ddd;
        }
        .tab {
            padding: 10px 20px;
            cursor: pointer;
            background-color: #f0f0f0;
            border: 1px solid #ddd;
            border-bottom: none;
            border-radius: 5px 5px 0 0;
            margin-right: 5px;
        }
        .tab.active {
            background-color: white;
            font-weight: bold;
        }
        .tab-content {
            display: none;
        }
        .tab-content.active {
            display: block;
        }
        .input-group {
            display: flex;
            margin-bottom: 20px;
        }
        #question {
            flex: 1;
            padding: 12px;
            border: 2px solid #ddd;
            border-radius: 5px;
            font-size: 16px;
        }
        #question:focus {
            outline: none;
            border-color: #4CAF50;
        }
        button {
            background-color: #4CAF50;
            color: white;
            border: none;
            padding: 12px 20px;
            margin-left: 10px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
        }
        button:hover {
            background-color: #45a049;
        }
        button:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }
        .btn-secondary {
            background-color: #2196F3;
        }
        .btn-secondary:hover {
            background-color: #1976D2;
        }
        .btn-danger {
            background-color: #f44336;
        }
        .btn-danger:hover {
            background-color: #d32f2f;
        }
        .btn-primary {
            background-color: #9C27B0;
        }
        .btn-primary:hover {
            background-color: #7B1FA2;
        }
        #answer {
            background-color: #f9f9f9;
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 20px;
            min-height: 100px;
        }
        .loading {
            color: #666;
            font-style: italic;
        }
        .error {
            color: #d32f2f;
            background-color: #ffebee;
            padding: 10px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        .success {
            color: #388e3c;
            background-color: #e8f5e9;
            padding: 10px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        .history-item {
            border-bottom: 1px solid #eee;
            padding: 10px 0;
        }
        .question {
            font-weight: bold;
            color: #333;
        }
        .answer {
            color: #666;
            margin-top: 5px;
        }
        #history {
            margin-top: 30px;
            max-height: 300px;
            overflow-y: auto;
        }
        .upload-area {
            border: 2px dashed #ccc;
            border-radius: 5px;
            padding: 30px;
            text-align: center;
            margin-bottom: 20px;
            cursor: pointer;
        }
        .upload-area:hover {
            border-color: #4CAF50;
        }
        .upload-area.dragover {
            background-color: #e8f5e9;
            border-color: #4CAF50;
        }
        .file-info {
            margin-top: 10px;
            font-size: 14px;
            color: #666;
        }
        .status-card {
            background-color: #f5f5f5;
            border-radius: 5px;
            padding: 15px;
            margin-bottom: 15px;
        }
        .status-item {
            display: flex;
            justify-content: space-between;
            padding: 5px 0;
            border-bottom: 1px solid #eee;
        }
        .status-item:last-child {
            border-bottom: none;
        }
        .doc-preview {
            background-color: #f9f9f9;
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 15px;
            margin-bottom: 15px;
        }
        .doc-id {
            font-weight: bold;
            color: #1976D2;
        }
        .doc-content {
            margin: 10px 0;
            font-size: 14px;
            color: #555;
        }
        .doc-meta {
            font-size: 12px;
            color: #888;
        }
        .conversation {
            max-height: 400px;
            overflow-y: auto;
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 15px;
            margin-bottom: 20px;
        }
        .message {
            margin-bottom: 15px;
            padding: 10px;
            border-radius: 5px;
        }
        .user-message {
            background-color: #e3f2fd;
            text-align: right;
        }
        .bot-message {
            background-color: #f5f5f5;
        }
        .message-sender {
            font-weight: bold;
            margin-bottom: 5px;
        }
        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            margin: 20px 0;
        }
        .pagination button {
            margin: 0 5px;
            padding: 8px 12px;
        }
        .pagination .page-info {
            margin: 0 15px;
            font-size: 14px;
            color: #666;
        }
        .pagination .current-page {
            background-color: #4CAF50;
            color: white;
        }
        .pagination .disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="tabs">
            <div class="tab active" data-tab="chat">💬 问答对话</div>
            <div class="tab" data-tab="upload">📁 文件上传</div>
            <div class="tab" data-tab="database">📊 数据库查看</div>
            <div class="tab" data-tab="status">⚙️ 系统状态</div>
        </div>
        
        <!-- 问答对话界面 -->
        <div id="chat" class="tab-content active">
            <div class="conversation" id="conversation">
                <div class="message bot-message">
                    <div class="message-sender">助手</div>
                    <div class="message-content">您好！我是您的本地知识库问答助手。请问有什么我可以帮您的吗？</div>
                </div>
            </div>
            
            <div class="input-group">
                <input type="text" id="question" placeholder="请输入您的问题..." autocomplete="off">
                <button id="ask-btn">提问</button>
            </div>
            
            <div id="chat-error" class="error" style="display: none;"></div>
        </div>
        
        <!-- 文件上传界面 -->
        <div id="upload" class="tab-content">
            <h2>上传文档到知识库</h2>
            <p>支持上传.txt格式的文本文件，上传后将自动添加到知识库中。</p>
            
            <div class="upload-area" id="upload-area">
                <p>点击选择文件或拖拽文件到此处</p>
                <p class="file-info">支持.txt文件，最大16MB</p>
                <input type="file" id="file-input" accept=".txt" style="display: none;">
            </div>
            
            <button id="upload-btn" disabled>上传文件</button>
            
            <div id="upload-result"></div>
        </div>
        
        <!-- 数据库查看界面 -->
        <div id="database" class="tab-content">
            <h2>向量数据库信息</h2>
            <button id="refresh-db" class="btn-secondary">刷新数据</button>
            
            <div id="database-info">
                <div class="loading">正在加载数据库信息...</div>
            </div>
        </div>
        
        <!-- 系统状态界面 -->
        <div id="status" class="tab-content">
            <h2>系统状态</h2>
            <button id="refresh-status" class="btn-secondary">刷新状态</button>
            <button id="reinit-btn" class="btn-danger" style="margin-left: 10px;">重新初始化系统</button>
            
            <div id="system-status">
                <div class="loading">正在加载系统状态...</div>
            </div>
        </div>
    </div>

    <script>
        // 当前活动的标签
        let activeTab = 'chat';
        let currentFile = null;
        let currentPage = 1;
        let totalPages = 1;
        
        // DOM元素
        const tabElements = document.querySelectorAll('.tab');
        const tabContentElements = document.querySelectorAll('.tab-content');
        const questionInput = document.getElementById('question');
        const askBtn = document.getElementById('ask-btn');
        const conversationDiv = document.getElementById('conversation');
        const chatErrorDiv = document.getElementById('chat-error');
        const uploadArea = document.getElementById('upload-area');
        const fileInput = document.getElementById('file-input');
        const uploadBtn = document.getElementById('upload-btn');
        const uploadResult = document.getElementById('upload-result');
        const refreshDbBtn = document.getElementById('refresh-db');
        const databaseInfoDiv = document.getElementById('database-info');
        const refreshStatusBtn = document.getElementById('refresh-status');
        const systemStatusDiv = document.getElementById('system-status');
        const reinitBtn = document.getElementById('reinit-btn');
        
        // 标签切换
        tabElements.forEach(tab => {
            tab.addEventListener('click', () => {
                const tabName = tab.getAttribute('data-tab');
                switchTab(tabName);
            });
        });
        
        function switchTab(tabName) {
            // 更新标签样式
            tabElements.forEach(tab => {
                if (tab.getAttribute('data-tab') === tabName) {
                    tab.classList.add('active');
                } else {
                    tab.classList.remove('active');
                }
            });
            
            // 显示对应内容
            tabContentElements.forEach(content => {
                if (content.id === tabName) {
                    content.classList.add('active');
                } else {
                    content.classList.remove('active');
                }
            });
            
            activeTab = tabName;
            
            // 根据当前标签执行相应操作
            if (tabName === 'database') {
                loadDatabaseInfo(1); // 加载第一页
            } else if (tabName === 'status') {
                loadSystemStatus();
            }
        }
        
        // 问答功能
        async function askQuestion() {
            const question = questionInput.value.trim();
            
            if (!question) {
                showError('chat', '请输入问题');
                return;
            }
            
            // 添加用户问题到对话
            addMessageToConversation('user', question);
            questionInput.value = '';
            
            // 显示加载状态
            askBtn.disabled = true;
            
            try {
                const response = await fetch('/ask', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ question })
                });
                
                const data = await response.json();
                
                if (response.ok) {
                    addMessageToConversation('bot', data.answer);
                } else {
                    showError('chat', data.error || '服务器错误');
                }
            } catch (error) {
                showError('chat', '网络错误: ' + error.message);
            } finally {
                askBtn.disabled = false;
                questionInput.focus();
            }
        }
        
        function addMessageToConversation(sender, content) {
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${sender}-message`;
            
            const senderName = sender === 'user' ? '您' : '助手';
            messageDiv.innerHTML = `
                <div class="message-sender">${senderName}</div>
                <div class="message-content">${content}</div>
            `;
            
            conversationDiv.appendChild(messageDiv);
            conversationDiv.scrollTop = conversationDiv.scrollHeight;
        }
        
        // 文件上传功能
        uploadArea.addEventListener('click', () => {
            fileInput.click();
        });
        
        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.classList.add('dragover');
        });
        
        uploadArea.addEventListener('dragleave', () => {
            uploadArea.classList.remove('dragover');
        });
        
        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
            
            if (e.dataTransfer.files.length) {
                handleFileSelect(e.dataTransfer.files[0]);
            }
        });
        
        fileInput.addEventListener('change', (e) => {
            if (e.target.files.length) {
                handleFileSelect(e.target.files[0]);
            }
        });
        
        function handleFileSelect(file) {
            if (!file.name.endsWith('.txt')) {
                showError('upload', '只支持.txt文件');
                return;
            }
            
            currentFile = file;
            uploadBtn.disabled = false;
            uploadArea.innerHTML = `
                <p>已选择文件: ${file.name}</p>
                <p>文件大小: ${(file.size / 1024).toFixed(2)} KB</p>
            `;
        }
        
        uploadBtn.addEventListener('click', uploadFile);
        
        async function uploadFile() {
            if (!currentFile) {
                showError('upload', '请先选择文件');
                return;
            }
            
            const formData = new FormData();
            formData.append('file', currentFile);
            
            uploadBtn.disabled = true;
            uploadResult.innerHTML = '<div class="loading">正在上传文件...</div>';
            
            try {
                const response = await fetch('/upload', {
                    method: 'POST',
                    body: formData
                });
                
                const data = await response.json();
                
                if (response.ok) {
                    showSuccess('upload', data.message);
                    // 重置上传区域
                    uploadArea.innerHTML = `
                        <p>点击选择文件或拖拽文件到此处</p>
                        <p class="file-info">支持.txt文件，最大16MB</p>
                    `;
                    fileInput.value = '';
                    currentFile = null;
                } else {
                    showError('upload', data.error || '上传失败');
                }
            } catch (error) {
                showError('upload', '上传失败: ' + error.message);
            } finally {
                uploadBtn.disabled = false;
            }
        }
        
        // 数据库查看功能
        refreshDbBtn.addEventListener('click', () => loadDatabaseInfo(1));
        
        async function loadDatabaseInfo(page = 1) {
            databaseInfoDiv.innerHTML = '<div class="loading">正在加载数据库信息...</div>';
            
            try {
                const response = await fetch(`/database/info?page=${page}&per_page=5`);
                const data = await response.json();
                
                if (response.ok) {
                    displayDatabaseInfo(data);
                } else {
                    databaseInfoDiv.innerHTML = `<div class="error">加载失败: ${data.error}</div>`;
                }
            } catch (error) {
                databaseInfoDiv.innerHTML = `<div class="error">加载失败: ${error.message}</div>`;
            }
        }
        
        function displayDatabaseInfo(data) {
            currentPage = data.current_page;
            totalPages = data.total_pages;
            
            let html = `
                <div class="status-card">
                    <div class="status-item">
                        <span>文档总数:</span>
                        <span>${data.document_count}</span>
                    </div>
                </div>
                
                <h3>文档预览 (第 ${currentPage} 页，共 ${totalPages} 页)</h3>
            `;
            
            if (data.document_previews && data.document_previews.length > 0) {
                data.document_previews.forEach(doc => {
                    html += `
                        <div class="doc-preview">
                            <div class="doc-id">ID: ${doc.id}</div>
                            <div class="doc-content">${doc.content}</div>
                            <div class="doc-meta">元数据: ${JSON.stringify(doc.metadata)}</div>
                        </div>
                    `;
                });
            } else {
                html += '<p>暂无文档</p>';
            }
            
            // 添加分页控件
            html += createPaginationControls(currentPage, totalPages);
            
            databaseInfoDiv.innerHTML = html;
            
            // 为分页按钮添加事件监听器
            document.querySelectorAll('.pagination-btn').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const page = parseInt(e.target.getAttribute('data-page'));
                    if (page && page !== currentPage) {
                        loadDatabaseInfo(page);
                    }
                });
            });
        }
        
        function createPaginationControls(currentPage, totalPages) {
            if (totalPages <= 1) return '';
            
            let html = '<div class="pagination">';
            
            // 上一页按钮
            if (currentPage > 1) {
                html += `<button class="pagination-btn" data-page="${currentPage - 1}">上一页</button>`;
            } else {
                html += '<button class="pagination-btn disabled">上一页</button>';
            }
            
            // 页码信息
            html += `<span class="page-info">第 ${currentPage} 页 / 共 ${totalPages} 页</span>`;
            
            // 下一页按钮
            if (currentPage < totalPages) {
                html += `<button class="pagination-btn" data-page="${currentPage + 1}">下一页</button>`;
            } else {
                html += '<button class="pagination-btn disabled">下一页</button>';
            }
            
            html += '</div>';
            
            return html;
        }
        
        // 系统状态功能
        refreshStatusBtn.addEventListener('click', loadSystemStatus);
        reinitBtn.addEventListener('click', reinitSystem);
        
        async function loadSystemStatus() {
            systemStatusDiv.innerHTML = '<div class="loading">正在加载系统状态...</div>';
            
            try {
                const response = await fetch('/system/status');
                const data = await response.json();
                
                if (response.ok) {
                    displaySystemStatus(data);
                } else {
                    systemStatusDiv.innerHTML = `<div class="error">加载失败: ${data.error}</div>`;
                }
            } catch (error) {
                systemStatusDiv.innerHTML = `<div class="error">加载失败: ${error.message}</div>`;
            }
        }
        
        function displaySystemStatus(data) {
            let html = `
                <div class="status-card">
                    <div class="status-item">
                        <span>系统状态:</span>
                        <span>${data.status}</span>
                    </div>
                    <div class="status-item">
                        <span>文档数量:</span>
                        <span>${data.document_count}</span>
                    </div>
                </div>
            `;
            
            systemStatusDiv.innerHTML = html;
        }
        
        async function reinitSystem() {
            if (confirm('确定要重新初始化系统吗？这将重新加载所有文档。')) {
                reinitBtn.disabled = true;
                reinitBtn.textContent = '正在初始化...';
                
                try {
                    const response = await fetch('/reinit', {
                        method: 'POST'
                    });
                    
                    const data = await response.json();
                    
                    if (response.ok) {
                        showSuccess('status', data.message);
                        // 刷新状态显示
                        setTimeout(loadSystemStatus, 1000);
                    } else {
                        showError('status', data.error || '重新初始化失败');
                    }
                } catch (error) {
                    showError('status', '重新初始化失败: ' + error.message);
                } finally {
                    reinitBtn.disabled = false;
                    reinitBtn.textContent = '重新初始化系统';
                }
            }
        }
        
        // 显示错误信息
        function showError(type, message) {
            const errorDiv = type === 'chat' ? chatErrorDiv : 
                           type === 'upload' ? uploadResult : 
                           type === 'status' ? systemStatusDiv : null;
            
            if (errorDiv) {
                errorDiv.textContent = message;
                errorDiv.className = 'error';
                errorDiv.style.display = 'block';
                
                // 3秒后自动隐藏
                setTimeout(() => {
                    errorDiv.style.display = 'none';
                }, 3000);
            }
        }
        
        // 显示成功信息
        function showSuccess(type, message) {
            const resultDiv = type === 'upload' ? uploadResult : null;
            
            if (resultDiv) {
                resultDiv.textContent = message;
                resultDiv.className = 'success';
                
                // 3秒后自动隐藏
                setTimeout(() => {
                    resultDiv.style.display = 'none';
                }, 3000);
            }
        }
        
        // 事件监听
        askBtn.addEventListener('click', askQuestion);
        
        questionInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                askQuestion();
            }
        });
        
        // 页面加载完成后初始化
        window.addEventListener('load', () => {
            questionInput.focus();
            loadSystemStatus();
        });
    </script>
</body>
</html>